package com.lonely.common.utils.oss;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lonely.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * picgo 图床工具类
 */
@Slf4j
public class PicGoUtil {

    // API Key 和上传地址常量
    private static final String UPLOAD_URL = "https://www.picgo.net/api/1/upload";
    private static final String API_KEY = "chv_S4JXq_2f58670001e00dae20231f83cc19a58d0bfe87ec1933316fde66735650ed3c0350748d23ef0a81ab9fe7cc512990fd4997eb70d88febd178b81b97204f025bca";

    // 设置带超时配置的 RestTemplate
    private static RestTemplate getRestTemplateWithTimeout() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(10000); // 连接超时时间，单位为毫秒
        factory.setReadTimeout(10000);    // 读取超时时间，单位为毫秒
        return new RestTemplate(factory);
    }

    // 上传文件
    public static String uploadFile(MultipartFile file, String fileName) {
        try {
            // 使用带超时配置的 RestTemplate
            RestTemplate restTemplate = getRestTemplateWithTimeout();

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 构建请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("key", API_KEY);  // API Key
            body.add("source", file.getResource());  // 上传文件
            // 相册 ID，该参数非必需，没有创建相册可自己修改代码删除
            // body.add("album_id", "你自己的相册 ID");  /
            body.add("title", fileName);  // 文件名
            body.add("format", "json");  // 响应格式

            HttpEntity<MultiValueMap<String, Object>> requestEntity =
                    new HttpEntity<>(body, headers);

            // 发送请求并获取 JSON 响应字符串
            ResponseEntity<String> responseEntity = restTemplate.exchange(UPLOAD_URL,
                    HttpMethod.POST, requestEntity, String.class);
            String responseJson = responseEntity.getBody();

            if (responseJson != null) {
                // 使用 FastJSON 解析 JSON
                JSONObject responseObject = JSON.parseObject(responseJson);

                // 提取返回结果中的信息
                if (responseObject.containsKey("image")) {
                    JSONObject imageInfo = responseObject.getJSONObject("image");
                    return imageInfo.getString("url"); // 返回图片的 URL
                } else if (responseObject.containsKey("error")) {
                    JSONObject errorInfo = responseObject.getJSONObject("error");
                    throw new BusinessException(errorInfo.getString("message"));
                }
            }

            throw new BusinessException("文件上传失败");
        } catch (Exception e) {
            log.error("文件上传失败，异常原因：{}", ExceptionUtils.getStackTrace(e));
            throw new BusinessException(String.format("文件上传失败,失败原因：%s", e.getMessage()));
        }
    }
}